package com.lbt.weixin.server.controller;

import java.util.List;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lbt.framework.exception.MyException;
import com.lbt.framework.jackson.result.ObjectResult;
import com.lbt.framework.jackson.result.StatusResult;
import com.lbt.weixin.common.bean.entity.Car;
import com.lbt.weixin.common.bean.entity.User;
import com.lbt.weixin.common.service.CarService;
import com.lbt.weixin.server.common.DateUtil;
import com.lbt.weixin.server.common.LbtUtil;
import com.lbt.weixin.server.jackson.filter.UserFilter;

/**
 * 登录授权
 * @author Moyq5
 * @date 2016年9月19日
 */
@Controller
@RequestMapping("/user")
public class UserController extends BaseController {
	
	private static Logger log = LoggerFactory.getLogger(UserController.class);
	
	@Resource
	CarService carService;
	@Resource
	ObjectMapper objectMapper;
	
	@RequestMapping
	@ResponseBody
	public ObjectResult<User> get(HttpServletRequest request) throws MyException {
		ObjectResult<User> result = new ObjectResult<User>();
		result.setFilter(UserFilter.getWithCars());
		long userId = checkBind(request);
		User user = userService.one(userId);
		result.setResult(user);
		result.setOk();
		return result;
	}
	
	@RequestMapping("/checklogin")
	@ResponseBody
	public StatusResult checklogin(HttpServletRequest request) throws MyException {
		checkBind(request);
		return new StatusResult();
	}
	
	@RequestMapping("/bind")
	@ResponseBody
	public StatusResult bind(String carNo, String mobile, String beginDate, HttpServletRequest request) throws MyException {
		long userId = checkLogin(request);
		log.debug("用户绑定: userId={}, carCardsNo={}, telephone={}", 
				new Object[] {userId, carNo, mobile});
		
		String p = "{\"CarCardsNo\":\""+ carNo +"\",\"Telephone\":\""+ mobile +"\",\"BeginDate\":\""+ beginDate +"\"}";
		LbtUtil.getApiResult(p, "checkuser");
		
		// 绑定手机号
		User user = userService.one(userId);
		if (null != user.getMobile() && !user.getMobile().equals(mobile)) {
			throw new MyException("您已经绑定过其它号码，不能重复绑定");
		} else if (null == user.getMobile()) {
			User existUser = new User();
			existUser.setMobile(mobile);
			int count = userService.count(existUser);
			if (count > 0) {
				throw new MyException("对不起，该手机号已经被其它用户绑定");
			}
			user.setMobile(mobile);
			user = userService.merge(user);
		}
		
		// 添加车牌信息
		Car car = new Car();
		car.setCarNo(carNo);
		car.setUser(user);
		int count = carService.count(car);
		if (count == 0) {
			car.setAddTime(DateUtil.getTimeStamp());
			car.setIsDefault(true);
			carService.persist(car);
		}
		
		StatusResult result = new StatusResult();
		result.setOk();
		return result;
	}
	
	@RequestMapping("/unbind")
	@ResponseBody
	public StatusResult unbind(long carId, HttpServletRequest request) throws MyException {
		long userId = checkLogin(request);
		log.debug("车辆解绑: userId={}, carId={}", 
				new Object[] {userId, carId});
		
		Car car = carService.one(carId);
		if (null != car && car.getUser().getUserId() == userId) {
			carService.delete(car);
		}
		
		StatusResult result = new StatusResult();
		result.setOk();
		return result;
	}
	
	@RequestMapping("/qryrepair")
	@ResponseBody
	public ObjectResult<?> qryrepair(String soNbr, String carNo, String page, String rows, HttpServletRequest request) throws MyException {
		long userId = checkBind(request);
		String p = "";
		if (StringUtils.isEmpty(soNbr)) {
			if (StringUtils.isEmpty(carNo)) {
				carNo = getDefaultCarNo(userId);
			}
			log.debug("查询维修记录: carCardsNo={}, page={}", carNo, page);
			p = "{\"type\":\"1\",\"CarCardsNo\":\""+ carNo +"\",\"page\":\""+ page +"\",\"rows\":\""+ rows +"\"}";
		} else {
			log.debug("查询维修记录: soNbr={}, page={}", soNbr, page);
			p = "{\"type\":\"2\",\"SoNbr\":\""+ soNbr +"\",\"page\":\""+ page +"\",\"rows\":\""+ rows +"\"}";
		}
		
		String apiResult = LbtUtil.getApiResult(p, "qryrepair");
		
		ObjectResult<String> result = new ObjectResult<String>();
		result.setResult(apiResult);
		result.setOk();
		return result;
	}
	
	@RequestMapping("/qryvip")
	@ResponseBody
	public ObjectResult<?> qryvip(String carNo, HttpServletRequest request) throws MyException {
		carNo = checkCarNo(request, carNo);
		
		log.debug("查询积分: carNo={}", carNo);
		
		String p = "{\"CarCardsNo\":\""+ carNo +"\"}";
		String apiResult = LbtUtil.getApiResult(p, "qryvip");
		
		ObjectResult<String> result = new ObjectResult<String>();
		result.setResult(apiResult);
		result.setOk();
		return result;
	}
	
	@RequestMapping("/satisfy")
	@ResponseBody
	public StatusResult satisfy(String soNbr, String satisfy, String remark, HttpServletRequest request) throws MyException {
		long userId = checkBind(request);
		log.debug("服务评价: userId={}, soNbr={}, satisfy={}", new Object[]{userId, soNbr, satisfy});
		
		String p = "{\"SoNbr\":\""+ soNbr +"\",\"Satisfy\":\""+ satisfy +"\",\"Remark\":\""+ remark +"\"}";
		LbtUtil.getApiResult(p, "satisfy");
		// TODO 根据单号，在这里检查用户是否有权限进行该评价。。。
		StatusResult result = new StatusResult();
		result.setOk();
		return result;
	}
	
	
	/**
	 * 查询养护设置
	 */
	@RequestMapping("/qrycare")
	@ResponseBody
	public ObjectResult<?> qryCare(String carNo, HttpServletRequest request) throws MyException {
		carNo = checkCarNo(request, carNo);
		
		log.debug("查询养护提醒设置信息: carNo={}", carNo);
		
		String p = "{\"CarCardsNo\":\""+ carNo +"\"}";
		String apiResult = LbtUtil.getApiResult(p, "qrycare");
		
		ObjectResult<String> result = new ObjectResult<String>();
		result.setResult(apiResult);
		result.setOk();
		return result;
	}
	
	/**
	 * 养护设置
	 */
	@RequestMapping(value = "/setcare")
	@ResponseBody
	public StatusResult setCare(String carCardsNo, String careMiles, String careMons, String cardDate, String insureDate, HttpServletRequest request) throws MyException {
		carCardsNo = checkCarNo(request, carCardsNo);
		log.debug("养护设置: {}", carCardsNo);
		
		String p = "{\"CarCardsNo\":\""+ carCardsNo +"\",\"CareMiles\":\""+ careMiles +"\",\"CareMons\":\""+ careMons +"\",\"CardDate\":\""+ cardDate +"\",\"InsureDate\":\""+ insureDate +"\"}";
		LbtUtil.getApiResult(p, "setcare");
		
		StatusResult result = new StatusResult();
		result.setOk();
		return result;
	}

	private String getDefaultCarNo(long userId) {
		String carNo = null;
		// 找出默认车辆
		User user = userService.one(userId);
		Set<Car> cars = user.getCars();
		for (Car car : cars) {
			if (car.getIsDefault()) {
				carNo = car.getCarNo();
			}
		} 
		// 设置（旧版本数据）默认车辆
		if (null == carNo && !cars.isEmpty()) {
			Car car = cars.iterator().next();
			car.setIsDefault(true);
			carService.merge(car);
			carNo = car.getCarNo();
		}
		return carNo;
	}
	
	private String checkCarNo(HttpServletRequest request, String carNo) {
		if (null != carNo) {
			long userId = checkBind(request);
			User user = new User();
			user.setUserId(userId);
			Car car = new Car();
			car.setUser(user);
			car.setCarNo(carNo);
			int count = carService.count(car);
			if (count == 0) {
				throw new MyException();
			}
		} else {
			carNo = getCarNo(request);
		}
		return carNo;
	}
}
